#!/bin/sh

# shellcheck disable=SC1091
. /usr/libexec/os-helpers-logging

KERNEL_IMAGE="${ROOTFS_DIR}/boot/@@KERNEL_IMAGETYPE@@"

kexec_enabled() {
    # The script is enabled if and only if we are in balena bootloader.
    # Any additional pre-conditions should be handled by runtime checks
    # in kexec_run(). This is because this script serves as exit point
    # for the balena bootloader, regardless of whether the actual kexec
    # call succeeds or not. Running any further initrd scripts
    # is undesirable and considered undefined behavior.
    if [ "$bootparam_balena_stage2" = "true" ]
    then
        return 0
    fi

    return 1
}

kexec_run() {
    if [ -z "${ROOTFS_DIR}" ]
    then
        fail "ROOTFS_DIR undefined, can not kexec"
    fi

    if [ ! -f "${KERNEL_IMAGE}" ]
    then
        fail "${KERNEL_IMAGE} not found, can not kexec"
    fi

    ROOT_UUID=$(findmnt "${ROOTFS_DIR}" -n -o UUID)

    # Remove the following kernel arguments:
    # * balena_stage2 - not to enter this script again after kexec
    # * root=XXX - will be replaced by the UUID
    # * maxcpus=0 - enable SMP after reboot if the 2nd stage bootloader has it disabled
    BOOT_PARAMS="$(cat /proc/cmdline | sed -e s,balena_stage2,, | sed -e s,root=[^\ ]*,, | sed -e s,maxcpus=0,, | sed -e s,nr_cpus=[^\ ]*,,)"
    kexec -s -l "${KERNEL_IMAGE}" --append="${BOOT_PARAMS} root=UUID=${ROOT_UUID} ${KEXEC_EXTRA_ARGS}"

    umount "${ROOTFS_DIR}"

    kexec -e

    # The `kexec -e` above should be the only exit point from this script
    # If the code has somehow reached all the way down here, it means
    # kexec had failed and we must bail out immediately.
    fail "kexec failed with $?, abort"
}
